<template>
  <div class="space-y-4">
    <!-- 查询条件 -->
    <div class="card flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
      <input type="date" class="input flex-1" v-model="startDate" />
      <span class="text-center sm:text-left">至</span>
      <input type="date" class="input flex-1" v-model="endDate" />
      <select class="input flex-1" v-model="analysisType">
        <option value="overview">概览统计</option>
        <option value="trends">趋势分析</option>
      </select>
      <button class="btn-primary" @click="load" :disabled="loading">
        {{ loading ? '查询中...' : '查询' }}
      </button>
    </div>

    <!-- 概览统计 -->
    <div v-if="analysisType === 'overview'" class="space-y-4">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="card">
          <div class="text-sm text-gray-500 mb-1">总配方奶量</div>
          <div class="text-2xl font-bold text-primary">{{ overview.totalFormulaMl }} ml</div>
        </div>
        <div class="card">
          <div class="text-sm text-gray-500 mb-1">总母乳时长</div>
          <div class="text-2xl font-bold text-primary">{{ overview.totalBreastMinutes }} 分钟</div>
        </div>
        <div class="card">
          <div class="text-sm text-gray-500 mb-1">总睡眠时长</div>
          <div class="text-2xl font-bold text-primary">{{ overview.totalSleepMinutes }} 分钟</div>
        </div>
      </div>
      <div class="card">
        <div class="text-lg font-semibold mb-4">数据概览</div>
        <div ref="overviewChartRef" style="width: 100%; height: 360px;"></div>
      </div>
    </div>

    <!-- 趋势分析 -->
    <div v-if="analysisType === 'trends'" class="space-y-4">
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <div class="card">
          <div class="text-sm text-gray-500 mb-1">日均喂奶次数</div>
          <div class="text-2xl font-bold text-primary">{{ formatNumber(trendsData.averages?.dailyFeedings || 0) }}</div>
        </div>
        <div class="card">
          <div class="text-sm text-gray-500 mb-1">日均配方奶量</div>
          <div class="text-2xl font-bold text-primary">{{ formatNumber(trendsData.averages?.dailyFormulaMl || 0) }} ml</div>
        </div>
        <div class="card">
          <div class="text-sm text-gray-500 mb-1">日均换尿布次数</div>
          <div class="text-2xl font-bold text-primary">{{ formatNumber(trendsData.averages?.dailyDiapers || 0) }}</div>
        </div>
        <div class="card">
          <div class="text-sm text-gray-500 mb-1">日均睡眠时长</div>
          <div class="text-2xl font-bold text-primary">{{ formatNumber(trendsData.averages?.dailySleepMinutes || 0) }} 分钟</div>
        </div>
      </div>
      
      <!-- 趋势图表 -->
      <div class="card">
        <div class="text-lg font-semibold mb-4">一周趋势</div>
        <div ref="trendsChartRef" style="width: 100%; height: 400px; min-height: 400px;"></div>
        <div v-if="!trendsData.dailyStats.length" class="text-center text-gray-500 py-8">
          暂无趋势数据
        </div>
      </div>

      <!-- 详细数据表格 -->
      <div class="card">
        <div class="text-lg font-semibold mb-4">每日详细数据</div>
        <div class="overflow-x-auto">
          <table class="w-full text-sm">
            <thead>
              <tr class="border-b">
                <th class="text-left py-2">日期</th>
                <th class="text-right py-2">喂奶次数</th>
                <th class="text-right py-2">配方奶(ml)</th>
                <th class="text-right py-2">母乳(分钟)</th>
                <th class="text-right py-2">换尿布次数</th>
                <th class="text-right py-2">睡眠(分钟)</th>
                <th class="text-right py-2">哭闹(分钟)</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="day in trendsData.dailyStats" :key="day.date" class="border-b">
                <td class="py-2">{{ formatDate(day.date) }}</td>
                <td class="text-right py-2">{{ day.feedings?.count || 0 }}</td>
                <td class="text-right py-2">{{ day.feedings?.totalFormulaMl || 0 }}</td>
                <td class="text-right py-2">{{ day.feedings?.totalBreastMinutes || 0 }}</td>
                <td class="text-right py-2">{{ day.diapers?.count || 0 }}</td>
                <td class="text-right py-2">{{ day.sleeps?.totalMinutes || 0 }}</td>
                <td class="text-right py-2">{{ day.cries?.totalMinutes || 0 }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, onMounted, reactive, ref, watch, nextTick } from 'vue';
import { useUserStore } from '../stores/user';
import { type StatsOverviewPayload, API_CONFIG } from '../services/api';
import * as echarts from 'echarts';

// 临时解决方案：直接定义函数
async function statsOverview(payload: StatsOverviewPayload) {
  const token = localStorage.getItem('auth_token');
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/stats/overview`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

// 趋势分析接口
async function statsTrends(payload: { babyId: number; startDate: string; endDate: string; type: string }) {
  const token = localStorage.getItem('auth_token');
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/stats/trends`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

const userStore = useUserStore();
const today = new Date().toLocaleDateString('en-CA');
const startDate = ref<string>(today);
const endDate = ref<string>(today);
const analysisType = ref<string>('overview');
const overview = reactive({ totalFormulaMl: 0, totalBreastMinutes: 0, totalSleepMinutes: 0 });
const trendsData = reactive({ 
  period: '', 
  dailyStats: [] as any[], 
  averages: {} as any 
});
const loading = ref(false);
const overviewChartRef = ref<HTMLDivElement | null>(null);
const trendsChartRef = ref<HTMLDivElement | null>(null);
let overviewChart: echarts.ECharts | null = null;
let trendsChart: echarts.ECharts | null = null;

async function load() {
  if (!userStore.currentBabyId) return;
  loading.value = true;
  try {
    if (analysisType.value === 'overview') {
      await loadOverview();
    } else {
      await loadTrends();
    }
  } catch (error) {
    console.error('加载统计数据失败:', error);
  } finally {
    loading.value = false;
  }
}

async function loadOverview() {
  const payload: StatsOverviewPayload = {
    babyId: userStore.currentBabyId!,
    startDate: startDate.value,
    endDate: endDate.value
  };
  const res = await statsOverview(payload);
  overview.totalFormulaMl = res.totalFormulaMl || 0;
  overview.totalBreastMinutes = res.totalBreastMinutes || 0;
  overview.totalSleepMinutes = res.totalSleepMinutes || 0;
  updateOverviewChart();
}

async function loadTrends() {
  const payload = {
    babyId: userStore.currentBabyId!,
    startDate: startDate.value,
    endDate: endDate.value,
    type: 'WEEKLY'
  };
  const res = await statsTrends(payload);
  trendsData.period = res.period || '';
  trendsData.dailyStats = res.dailyStats || [];
  trendsData.averages = res.averages || {};
  
  // 等待DOM更新后再初始化图表
  await nextTick();
  
  // 确保图表容器存在后再更新
  if (!trendsChart && trendsChartRef.value) {
    trendsChart = echarts.init(trendsChartRef.value);
  }
  
  updateTrendsChart();
}

function renderCharts() {
  if (overviewChartRef.value) {
    overviewChart = echarts.init(overviewChartRef.value);
    updateOverviewChart();
  }
  if (trendsChartRef.value) {
    trendsChart = echarts.init(trendsChartRef.value);
    // 初始化时设置一个空的图表配置
    trendsChart.setOption({
      tooltip: { trigger: 'axis' },
      legend: { data: ['配方奶(ml)', '母乳(分钟)', '睡眠(分钟)', '换尿布次数'] },
      xAxis: { type: 'category', data: [] },
      yAxis: [{ type: 'value', name: '毫升/分钟', position: 'left' }],
      series: [
        { name: '配方奶(ml)', type: 'line', data: [] },
        { name: '母乳(分钟)', type: 'line', data: [] },
        { name: '睡眠(分钟)', type: 'line', data: [] },
        { name: '换尿布次数', type: 'bar', data: [] }
      ]
    });
  }
  window.addEventListener('resize', handleResize);
}

function updateOverviewChart() {
  if (!overviewChart) return;
  overviewChart.setOption({
    tooltip: {},
    xAxis: {
      data: ['配方奶 (ml)', '母乳 (分)', '睡眠 (分)']
    },
    yAxis: {},
    series: [{
      name: '统计',
      type: 'bar',
      data: [overview.totalFormulaMl, overview.totalBreastMinutes, overview.totalSleepMinutes],
      itemStyle: { color: '#FFB6C1' }
    }]
  });
}

function updateTrendsChart() {
  if (!trendsData.dailyStats.length) {
    console.log('没有趋势数据');
    return;
  }
  
  // 如果图表未初始化，尝试初始化
  if (!trendsChart && trendsChartRef.value) {
    trendsChart = echarts.init(trendsChartRef.value);
  }
  
  if (!trendsChart) {
    console.log('趋势图表未初始化');
    return;
  }
  
  console.log('更新趋势图表，数据:', trendsData.dailyStats);
  
  const dates = trendsData.dailyStats.map(day => formatDate(day.date));
  const formulaData = trendsData.dailyStats.map(day => day.feedings?.totalFormulaMl || 0);
  const breastData = trendsData.dailyStats.map(day => day.feedings?.totalBreastMinutes || 0);
  const sleepData = trendsData.dailyStats.map(day => day.sleeps?.totalMinutes || 0);
  const diaperData = trendsData.dailyStats.map(day => day.diapers?.count || 0);
  
  console.log('图表数据:', { dates, formulaData, breastData, sleepData, diaperData });
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['配方奶(ml)', '母乳(分钟)', '睡眠(分钟)', '换尿布次数']
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value',
      name: '数值'
    },
    series: [
      {
        name: '配方奶(ml)',
        type: 'line',
        data: formulaData,
        smooth: true,
        itemStyle: { color: '#FF6B6B' },
        lineStyle: { width: 3 }
      },
      {
        name: '母乳(分钟)',
        type: 'line',
        data: breastData,
        smooth: true,
        itemStyle: { color: '#4ECDC4' },
        lineStyle: { width: 3 }
      },
      {
        name: '睡眠(分钟)',
        type: 'line',
        data: sleepData,
        smooth: true,
        itemStyle: { color: '#45B7D1' },
        lineStyle: { width: 3 }
      },
      {
        name: '换尿布次数',
        type: 'line',
        data: diaperData,
        smooth: true,
        itemStyle: { color: '#96CEB4' },
        lineStyle: { width: 3 }
      }
    ]
  };
  
  trendsChart.setOption(option, true); // 强制重新渲染
}

function formatDate(dateString: string) {
  return new Date(dateString).toLocaleDateString('zh-CN', { 
    month: 'short', 
    day: 'numeric' 
  });
}

function formatNumber(value: number): string {
  if (value === 0) return '0';
  if (Number.isInteger(value)) return value.toString();
  return value.toFixed(1);
}

function handleResize() { 
  if (overviewChart) overviewChart.resize(); 
  if (trendsChart) trendsChart.resize(); 
}

// 监听宝宝切换，重新加载数据
watch(() => userStore.currentBabyId, () => {
  if (userStore.currentBabyId) {
    load();
  }
});

// 监听分析类型切换
watch(() => analysisType.value, async () => {
  if (userStore.currentBabyId) {
    // 等待DOM更新
    await nextTick();
    // 重新初始化图表
    if (analysisType.value === 'trends' && trendsChartRef.value && !trendsChart) {
      trendsChart = echarts.init(trendsChartRef.value);
    }
    load();
  }
});

onMounted(() => { 
  renderCharts(); 
  load(); 
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  if (overviewChart) { 
    overviewChart.dispose(); 
    overviewChart = null; 
  }
  if (trendsChart) { 
    trendsChart.dispose(); 
    trendsChart = null; 
  }
});
</script>

<style scoped></style>